﻿using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using SharedLibraries;
using SharedLibraries.Constants;
using EntityObject;
using DataAccessObject;
using ThangNM_LIB.FUNC;
using ThangNM_LIB.DB;

namespace ThangNM.UserControl
{
    public partial class File_DetailUC : System.Web.UI.UserControl
    {
        #region "Properties & Event"
        public delegate void CustomerEventHandler(object sender, CustomerEventArgs args);
        public event CustomerEventHandler ViewMessage;
        public event EventHandler BackList;

        public Int16 iFunctionType
        {
            get { return (Int16)ViewState["iFunctionType"]; }
            set { ViewState["iFunctionType"] = value; }
        }

        public List<sLinkEO> lstLinkTemp
        {
            get { return (List<sLinkEO>)ViewState["lstLinkTemp"]; }
            set { ViewState["lstLinkTemp"] = value; }
        }

        public FileEO objTemp
        {
            get { return (FileEO)ViewState["objTemp"]; }
            set { ViewState["objTemp"] = value; }
        }
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                txtsEmbed.EnterMode = CKEditor.NET.EnterMode.BR;
                CKEditorEx.LoadCKEditor(txtsEmbed);
                if (!IsPostBack)
                {
                    ToolBarUC1.ViewGroupButtonByFunction(ConstEx.funcButtonToolBar.DETAIL);
                }
            }
            catch (Exception ex)
            {
                setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.ERROR, ex.Message, null));
            }
        }

        public void BindDataDetail(FileEO objInput, Int16 iFuncType)
        {
            objTemp = objInput;
            BindData_DropDownList();
            WebEx.setSelect_DropDownList(ddlFK_iAccountID, Convert.ToString(objInput.FK_iAccountID));
            txtsName.Text = objInput.sTitle;
            txtsDescription.Text = objInput.sDescription;
            txtsKeyword.Text = objInput.sKeyword;
            txtsLinkImage.Text = objInput.sLinkImage;
            txtsLinkImageThumbnail.Text = objInput.sLinkImageThumbnail;
            txtsUrlRewrite.Text = objInput.sUrlRewrite;
            txtsUrlShort.Text = objInput.sUrlShort;
            WebEx.setText_InputDefault(txtfPriority, Convert.ToString(objInput.fPriority), "0.5");
            WebEx.setSelect_DropDownList(ddliChangefreq, Convert.ToString(objInput.iChangefreq));
            WebEx.setSelect_DropDownList(ddliRobots, Convert.ToString(objInput.iRobots));
            WebEx.setSelect_DropDownList(ddliStatus, Convert.ToString(objInput.iState));
            WebEx.setSelect_DropDownList(ddlFK_iCategoryID, Convert.ToString(objInput.FK_iCategoryID));
            WebEx.setText_InputDefault(txtiLike, Convert.ToString(objInput.iLike), "0");
            WebEx.setText_InputDefault(txtiVisit, Convert.ToString(objInput.iVisit), "0");
            WebEx.setText_InputDefault(txtiComment, Convert.ToString(objInput.iComment), "0");
            WebEx.setText_InputDateTime(txttDateTimeCreate, objInput.tDateTimeCreate);
            WebEx.setText_InputDateTime(txttDateTimeModify, objInput.tDateTimeModify);


            txtsRecommend.Text = Convert.ToString(objInput.FK_sFileID);
            txtsEmbed.Text = Convert.ToString(objInput.sEmbed);
            txtsSize.Text = Convert.ToString(objInput.sSize);
            txtsHomepage.Text = Convert.ToString(objInput.sHomepage);
            chkbAdvertise.Checked = objInput.bAdvertise;

            lstLinkTemp = new List<sLinkEO>();
            object temp = JsonEx.Json2ListObject(objInput.sLinkDownload, lstLinkTemp.GetType());
            if (temp != null)
                lstLinkTemp = (List<sLinkEO>)temp;
            BindData();
            iFunctionType = iFuncType;
            ViewByFunction(iFunctionType);
        }

        protected void BindData_DropDownList()
        {
            ddlFK_iAccountID.DataSource = (new ShareDAO.UserDAO()).SelectBy_bState(null);
            ddlFK_iAccountID.DataValueField = "PK_iAccountID";
            ddlFK_iAccountID.DataTextField = "sUsername";
            ddlFK_iAccountID.DataBind();

            ddliChangefreq.DataSource = GetListConstants.Changefreq_GLC();
            ddliChangefreq.DataValueField = "Key";
            ddliChangefreq.DataTextField = "Value";
            ddliChangefreq.DataBind();

            ddliRobots.DataSource = GetListConstants.Robots_GLC();
            ddliRobots.DataValueField = "Key";
            ddliRobots.DataTextField = "Value";
            ddliRobots.DataBind();

            ddliStatus.DataSource = GetListConstants.Topic_iStatus_GLC(false);
            ddliStatus.DataValueField = "Key";
            ddliStatus.DataTextField = "Value";
            ddliStatus.DataBind();


            List<Category_ZipEO> lst = (from i in CustomerCache.get_lstCategory_ZipEO()
                                        where i.iType == ConstEx.TableID_C.File
                                        select i).ToList();
            ddlFK_iCategoryID.DataSource = lst;
            ddlFK_iCategoryID.DataValueField = "PK_iCategoryID";
            ddlFK_iCategoryID.DataTextField = "sName";
            ddlFK_iCategoryID.DataBind();
        }

        protected bool CheckInput()
        {
            string strNull = "";
            if (string.IsNullOrEmpty(txtsName.Text) == true)
            {
                strNull += ", " + lblsName.Text;
                txtsName.Focus();
            }
            if (string.IsNullOrEmpty(txtsDescription.Text) == true)
            {
                strNull += ", " + lblsDescription.Text;
                txtsDescription.Focus();
            }

            if (String.IsNullOrEmpty(strNull))
            {
                return true;
            }
            else
            {
                setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.WARNING, MessagesEx.CAC_TRUONG_BAT_BUOC_PHAI_NHAP + strNull.Substring(2).Replace(":", ""), null));
                return false;
            }
        }

        protected void GetObject(ref FileEO _FileEO)
        {
            try
            {
                _FileEO.PK_iTable = ConstEx.TableID_C.File;
                _FileEO.PK_iSEO = objTemp.PK_iSEO;
                _FileEO.FK_sAccount = ShareDAO.UserDAO.getPK_iAccountID(Convert.ToString(Session["secret"])).Name;
                _FileEO.FK_sCategory = WebEx.getSelect_DropDownList(ddlFK_iCategoryID, true);
                _FileEO.sTitle = Convert.ToString(txtsName.Text);
                _FileEO.sKeyword = StringEx.remove_dublicate_in_string_array(txtsKeyword.Text + "," + WebEx.getSelect_DropDownList(ddlFK_iCategoryID, false));
                _FileEO.sDescription = Convert.ToString(txtsDescription.Text);
                //_FileEO.sLinkMedia = OtherEx.getUrlStandard(txtsLinkMedia.Text);
                _FileEO.sLinkImage = OtherEx.getUrlStandard(txtsLinkImage.Text);
                _FileEO.sLinkImageThumbnail = OtherEx.getUrlStandard(txtsLinkImageThumbnail.Text);
                _FileEO.sUrlRewrite = Commons.get_sUrlRewrite_sUrlShort(_FileEO.PK_iTable, true, null, _FileEO.sTitle);
                _FileEO.sUrlShort = Commons.get_sUrlRewrite_sUrlShort(_FileEO.PK_iTable, false, null, _FileEO.sTitle);
                _FileEO.iChangefreq = Convert.ToInt16(ddliChangefreq.SelectedValue);
                _FileEO.iRobots = Convert.ToInt16(ddliRobots.SelectedValue);
                _FileEO.fPriority = Convert.ToDouble(txtfPriority.Text);
                _FileEO.FK_iAccountID = ShareDAO.UserDAO.getPK_iAccountID(Convert.ToString(Session["secret"])).Version;
                _FileEO.iStatus = Convert.ToInt16(ddliStatus.SelectedValue);
                _FileEO.bStatus = ConvertEx.Convert_iStatus_bStatus(_FileEO.iStatus);


                _FileEO.FK_sFileID = Convert.ToString(txtsRecommend.Text);
                _FileEO.sEmbed = Convert.ToString(txtsEmbed.Text);
                _FileEO.sSize = Convert.ToString(txtsSize.Text);
                _FileEO.sHomepage = OtherEx.getUrlStandard(txtsHomepage.Text);
                _FileEO.sLinkDownload = JsonEx.ListObject2Json(lstLinkTemp);
                _FileEO.bAdvertise = chkbAdvertise.Checked;
            }
            catch (Exception ex)
            {
                _FileEO = null;
                setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.ERROR, ex.Message, null));
            }
        }

        protected void ViewByFunction(Int16 iFuncType)
        {
            setEnableAllInput();
            switch (iFuncType)
            {
                case ConstEx.FunctionType.Insert:
                    ddlFK_iCategoryID.Enabled = true;
                    ToolBarUC1.ViewButtonByFunction(iFunctionType);
                    break;
                case ConstEx.FunctionType.Update: break;
                case ConstEx.FunctionType.Delete: break;
                case ConstEx.FunctionType.View:
                    ddlFK_iCategoryID.Enabled = false;
                    ToolBarUC1.ViewButtonByFunction(iFunctionType);
                    break;
            }
        }

        protected void setEnableAllInput()
        {
            ddlFK_iAccountID.Enabled = false;
            txttDateTimeCreate.Enabled = false;
            txttDateTimeModify.Enabled = false;
            txtiLike.Enabled = false;
            txtiVisit.Enabled = false;
            txtiComment.Enabled = false;
            txtsUrlRewrite.Enabled = false;
            txtsUrlShort.Enabled = false;
        }

        protected void EventButtonToolBar_Click(object sender, CustomerEventArgs e)
        {
            if (e.iType != ConstEx.funcButtonToolBar.BACK_LIST && (new ShareDAO.UserDAO()).SelectBy_sPermission(Session["secret"], Convert.ToString(Request.Url.AbsolutePath), e.iType) == false)
            {
                setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.DANGER, MessagesEx.Khong_Co_Quyen_Truy_Cap, null));
                Commons.setAccessDenied(Page, null);
                return;
            }
            switch (e.iType)
            {
                case ConstEx.funcButtonToolBar.INSERT_LIST: break;
                case ConstEx.funcButtonToolBar.INSERT_ITEM:
                    InsertItem();
                    break;
                case ConstEx.funcButtonToolBar.UPDATE_ITEM:
                    UpdateItem();
                    break;
                case ConstEx.funcButtonToolBar.DELETE_LIST: break;
                case ConstEx.funcButtonToolBar.DELETE_ITEM:
                    DeleteItem();
                    break;
                case ConstEx.funcButtonToolBar.REFRESH_LIST: break;
                case ConstEx.funcButtonToolBar.EXPORT_EXCEL: break;
                case ConstEx.funcButtonToolBar.RESET_FORM:
                    ResetForm();
                    break;
                case ConstEx.funcButtonToolBar.BACK_LIST:
                    if (BackList != null)
                        BackList(this, null);
                    break;
            }
        }

        protected void InsertItem()
        {
            try
            {
                if (CheckInput() == true)
                {
                    FileEO _FileEO = new FileEO();
                    GetObject(ref _FileEO);
                    if (_FileEO == null)
                        return;
                    if ((new FileDAO()).Insert_Update_Delete(ref _FileEO, 1) == true)
                    {
                        setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.SUCCESS, String.Format(MessagesEx.Them_Thanh_Cong_Ma_Ten, ConstEx.Table_Name_C.File, _FileEO.PK_iSEO, _FileEO.sTitle), null));
                    }
                    else
                    {
                        setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.WARNING, String.Format(MessagesEx.Them_That_Bai_Ma_Ten, ConstEx.Table_Name_C.File, _FileEO.PK_iSEO, _FileEO.sTitle), null));
                    }
                }
            }
            catch (Exception ex)
            {
                setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.ERROR, ex.Message, null));
            }
        }
        protected void UpdateItem()
        {
            try
            {
                if (CheckInput() == true)
                {
                    FileEO _FileEO = new FileEO();
                    GetObject(ref _FileEO);
                    if (_FileEO == null)
                        return;
                    if ((new FileDAO()).Insert_Update_Delete(ref _FileEO, 2) == true)
                    {
                        setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.SUCCESS, String.Format(MessagesEx.Sua_Thanh_Cong_Ma_Ten, ConstEx.Table_Name_C.File, _FileEO.PK_iSEO, _FileEO.sTitle), null));
                    }
                    else
                    {
                        setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.WARNING, String.Format(MessagesEx.Sua_That_Bai_Ma_Ten, ConstEx.Table_Name_C.File, _FileEO.PK_iSEO, _FileEO.sTitle), null));
                    }
                }
            }
            catch (Exception ex)
            {
                setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.ERROR, ex.Message, null));
            }
        }
        protected void DeleteItem()
        {
            try
            {
                FileEO _FileEO = new FileEO();
                GetObject(ref _FileEO);
                if (_FileEO == null)
                    return;
                if ((new FileDAO()).Insert_Update_Delete(ref _FileEO, 3) == true)
                {
                    setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.SUCCESS, String.Format(MessagesEx.Xoa_Thanh_Cong_Ma_Ten, ConstEx.Table_Name_C.File, _FileEO.PK_iSEO, _FileEO.sTitle), null));
                }
                else
                {
                    setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.WARNING, String.Format(MessagesEx.Xoa_That_Bai_Ma_Ten, ConstEx.Table_Name_C.File, _FileEO.PK_iSEO, _FileEO.sTitle), null));
                }
            }
            catch (Exception ex)
            {
                setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.ERROR, ex.Message, null));
            }
        }

        protected void ResetForm()
        {
            FileEO _FileEO = new FileEO();
            BindDataDetail(_FileEO, iFunctionType);
        }

        protected void btnInsert_Click(object sender, EventArgs e)
        {
            try
            {
                TextBox txtsLink_Temp = (TextBox)grvList.FooterRow.FindControl("txtsLink_Temp");
                TextBox txtsLinkAds_Temp = (TextBox)grvList.FooterRow.FindControl("txtsLinkAds_Temp");
                DropDownList ddliServer_Temp = (DropDownList)grvList.FooterRow.FindControl("ddliServer_Temp");
                CheckBox chkbStatus_Temp = (CheckBox)grvList.FooterRow.FindControl("chkbStatus_Temp");
                if (String.IsNullOrEmpty(StringEx.Trim(txtsLink_Temp.Text)))
                {
                    BindData();
                    MsgUC1.setNotifications(ConstEx.FunctionSetMsg.WARNING, "Link tải bắt buộc phải nhập.");
                    txtsLink_Temp.Focus();
                    return;
                }
                sLinkEO objLink = new sLinkEO();
                objLink.PK_iLinkID = 0;
                objLink.sLink = OtherEx.getUrlStandard(StringEx.Trim(txtsLink_Temp.Text));
                objLink.sLinkAds = OtherEx.getUrlStandard(StringEx.Trim(txtsLinkAds_Temp.Text));
                //objLink.iQuantity = 0;
                objLink.iServer = Convert.ToInt16(ddliServer_Temp.SelectedValue);
                objLink.bStatus = chkbStatus_Temp.Checked;
                lstLinkTemp.Insert(0, objLink);
                txtsLink_Temp.Text = "";
                txtsLinkAds_Temp.Text = "";
                ddliServer_Temp.SelectedIndex = 0;
                chkbStatus_Temp.Checked = true;
                BindData();
                MsgUC1.setNotifications(ConstEx.FunctionSetMsg.SUCCESS, "Thêm thành công.");
                txtsLink_Temp.Focus();
            }
            catch (Exception ex)
            {
                MsgUC1.setNotifications(ConstEx.FunctionSetMsg.ERROR, ex.Message);
            }
        }

        protected void BindData()
        {
            MsgUC1.setClearMsg();
            if (lstLinkTemp == null || lstLinkTemp.Count < 1)
            {
                lstLinkTemp = new List<sLinkEO>();
                lstLinkTemp.Insert(0, new sLinkEO());
            }
            if (lstLinkTemp.Count > 1)
            {
                var result = lstLinkTemp.FindAll(x => !String.IsNullOrEmpty(x.sLink));
                lstLinkTemp = result;
            }
            for (Int16 i = 0; i < lstLinkTemp.Count; i++)
            {
                lstLinkTemp[i].PK_iLinkID = Convert.ToInt16(i + 1);
            }
            grvList.DataSource = lstLinkTemp.ToList();
            grvList.DataBind();
            BindData_DDL();
        }

        protected void BindData_DDL()
        {
            DropDownList ddliServer_Temp = (DropDownList)grvList.FooterRow.FindControl("ddliServer_Temp");
            if (ddliServer_Temp != null)
            {
                ddliServer_Temp.DataSource = GetListConstants.File_iServer_GLC();
                ddliServer_Temp.DataValueField = "Key";
                ddliServer_Temp.DataTextField = "Value";
                ddliServer_Temp.DataBind();
            }
        }

        protected void grvList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "cmdDelete")
            {
                int id = Convert.ToInt32(e.CommandArgument);
                lstLinkTemp.RemoveAt(id);
                BindData();
                MsgUC1.setNotifications(ConstEx.FunctionSetMsg.SUCCESS, "Xóa thành công.");
            }
        }

        protected void grvList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Label lbliStatus = (Label)e.Row.FindControl("lbliServer");
                lbliStatus.Text = GetTextConstants.File_iServer_GTC(Convert.ToInt16(lbliStatus.Text));
            }
        }

        public void setViewMessage(object sender, CustomerEventArgs args)
        {
            if (ViewMessage != null)
                ViewMessage(sender, args);
        }
    }
}